package com.mygodp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mygodp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    public void set(String key,Object value,Long time,TimeUnit timeUnit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time, timeUnit);
    }

    public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit timeUnit){
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    //缓存击穿
    public <R,ID> R queryWithPassThrough
    (String keyPrefix, ID id, Class<R> type,Function<ID,R> dbFallback,Long time,TimeUnit timeUnit){
        String key= keyPrefix + id;
        //1.从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        // 只有当字符串是"abc"这种形式才返回true "" "/n" 这种都是false
        if(StrUtil.isNotBlank(json)){
            //3.存在，直接返回
            R r = JSONUtil.toBean(json, type);
            return r;
        }
        //判断命中是否为空值
        if(json!=null){
            return null;
        }
        //4.redis不存在，根据id查询数据库
        R r = dbFallback.apply(id);
        //5.数据库不存在，返回错误
        if (r==null){
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //6.数据库存在，写入redis并返回
        this.set(key,r,time,timeUnit);
        return r;
    }

    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);

    //逻辑过期解决缓存击穿
    public <R,ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type,Function<ID,R> dbFallback,Long time,TimeUnit timeUnit){
        String key= keyPrefix + id;
        //1.从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        // 只有当字符串是"abc"这种形式才返回true "" "/n" 这种都是false
        if(StrUtil.isBlank(json)){
            //3.不存在，返回空
            return null;
        }
        //4.命中 需要把json反序列成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //6.没过期 返回商铺
            return r;
        }
        String lockKey = key + id;
        //7.过期 尝试获取互斥锁
        boolean isLock = tryLock(lockKey);
        if(isLock){

            //8.获取成功开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    //1.查数据库
                    R rdata = dbFallback.apply(id);
                    setWithLogicalExpire(key,rdata,time,timeUnit);

                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(lockKey);
                }
            });

        }

        //9.获取失败 返回过期商铺信息
        return r;
    }
    private boolean tryLock(String key){
        boolean flag= stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
